<?php


namespace app\crm\model;

use think\facade\Db;
use app\admin\model\Common;

class TransferShop extends Common
{

    /**
     * 为了数据库的整洁，同时又不影响Model和Controller的名称
     * 我们约定每个模块的数据表都加上相同的前缀，比如CRM模块用crm作为数据表前缀
     */
    protected $name = 'customer_transfer_shop';

    /**
     * 列表
     * @param  array $request 请求参数
     * @return array
     * @author Mr.Huang
     * @create 2021-06-23 11:48
     */
    public function getDataList(array $request): array
    {
        // try {
            $request['page']  = isset($request['page']) && intval($request['page']) ? intval($request['page']) : 1;
            $request['limit'] = isset($request['limit']) && intval($request['limit']) ? intval($request['limit']) : 15;
            $customerName     = isset($request['customer_name']) && trim($request['customer_name']) ? trim($request['customer_name']) : '';
            $in_shop_id       = isset($request['in_shop_id']) ? intval($request['in_shop_id'])  : 0;
            $out_shop_id      = isset($request['out_shop_id']) ? intval($request['out_shop_id'])  : 0;
            $where            = [];
            if ($customerName) {
                $customerWhere = [
                    ['customer_name', 'like', '%' . $customerName . '%']
                ];
                $likeCustomerId = Db::name('customer')->where($customerWhere)->column('id');
                array_push($where, ['customer_id', 'in', $likeCustomerId]);
            }
            if ($in_shop_id) {
                $where['in_shop_id'] = $in_shop_id;
            }
            if ($out_shop_id) {
                $where['out_shop_id']= $out_shop_id;
            }
            $export = $request['export'] ?? 0;
            if ($export == 1){
                $ids = $request['id'] ?? [];
                array_push($where,['id','in',$ids]);
            }
            $shopIds = $request['shopIds'] ?? [];
            // if($shopIds){
            //     array_push($where,['in_shop_id','in',$shopIds]);
            // }
            $dataCount = $this->where($where)->count();
            if ($dataCount) {
                $field = ['id', 'customer_id', 'in_shop_id', 'out_shop_id', 'reason', 'create_time', 'update_time','operator'];
                $list  = $this
                        ->where($where)
                        ->when(!empty($shopIds), function ($query) use ($shopIds) {
                                $query->whereOr([
                                            ['in_shop_id','in',$shopIds],
                                            ['out_shop_id','in',$shopIds]
                                        ]);
                                    })
                        ->field($field)->order('id DESC')
                        ->limit(($request['page'] - 1) * $request['limit'], $request['limit'])
                        ->select()->toArray();

//                客户信息
                $customerIdArr = array_unique(array_column($list, 'customer_id'));
                $customerList  = Db::name('customer')->where('id', 'in', $customerIdArr)->column('customer_name', 'id');
//                店铺信息
                $inShopId  = array_unique(array_column($list, 'in_shop_id'));
                $outShopId = array_unique(array_column($list, 'out_shop_id'));
                $user_idId = array_unique(array_column($list, 'user_id'));
                $shopIdArr = array_unique(array_merge($inShopId, $outShopId,$user_idId));
                $shopList  = Db::name('shop')->where('shop_id', 'in', $shopIdArr)->column('shop_name', 'shop_id');
                //客服信息
                $operatorId  = array_values(array_unique(array_column($list, 'operator')));
                $userList  = Db::name('admin_user')->where('id', 'in', $operatorId)->column('realname', 'id');
                foreach ($list as $key => $val) {
                    $list[$key]['in_shop_name']  = $shopList[$val['in_shop_id']] ?? '';
                    $list[$key]['out_shop_name'] = $shopList[$val['out_shop_id']] ?? '';
                    $list[$key]['customer_name'] = $customerList[$val['customer_id']] ?? '';
                    $list[$key]['operator_name'] = $userList[$val['operator']] ?? '';
                }
            }

            $data              = [];
            $data['list']      = $list ?? [];
            $data['dataCount'] = $dataCount ?? 0;
            return $data;
        // } catch (\Exception $e) {
        // }

        $this->error = '暂无此数据';
        return [];
    }

    /**
     * 转店
     * @param  array $request 请求参数
     * @return bool
     * @author Mr.Liu Wuchen
     * @create 2021-06-23 13:45
     */
    public function addData(array $request): bool
    {
        // try {
            $validate = new \app\crm\validate\TransferShop();
            if (!$validate->scene('create')->check($request)) {
                $this->error = $validate->getError();
                return false;
            }

            $inShopId   = $request['in_shop_id'] ?? 0;
            $user_id   = $request['user_id'] ?? 0;
            $customerId = $request['customer_id'] ?? 0;
            $is_information = $request['is_information'] ?? 0;
            $info  = Db::name('customer')->where('id', '=', $customerId)->find();
            if (!$info) {
                $this->error = '获取转出店铺失败';
                return false;
            }
            $outShopId = $info['shop_id'];
            $inShopFind = Db::name('shop')->where('shop_id', '=', $inShopId)->find();
            $outShopFind = Db::name('shop')->where('shop_id', '=', $outShopId)->find();
            if(!$inShopFind){
                $this->error = '转入门店不存在';
                return false;
            }
            if ($outShopId == $inShopId) {
                // code...
                $this->error = '转入转出门店相同';
                return false;
            }
            //判断是否存在余额
            $customer_balanceList = Db::name('customer_balance')->where('customer_id', '=', $customerId)->select();
            foreach ($customer_balanceList as $key => $val){
                if($val['money'] != 0 || $val['complimentary_money'] != 0){
                    $this->error = '客户余额尚未处理，请先处理客户余额';
                    return false;
                }
            }
            $telephone = $info['telephone'];
            //判断是否是需要添加第二份客户数据
            if($outShopFind['shop_type'] == 1){
                if($inShopFind['shop_type'] == 1){//门诊转门诊可转
                }else{//门诊专门店，需要判断是否存在门店数据，需要判断是否该客户是否存在同类型门店的客户数据，存在则不可以转
                    $info_two  = Db::name('customer')->where([['id', '<>', $customerId],['telephone', '=', $telephone],['shop_id','=',$inShopId]])->find();
                    if($info_two){
                        $this->error = '客户在【'.$inShopFind['shop_name'].'】已存在资料，转入门店类型相同，无法转入';
                        return false;
                    }
                }
            }else{
                if($inShopFind['shop_type'] == 1){//门店转门诊可转，需要判断是否该客户是否存在同类型门店的客户数据，存在则不可以转
                    $info_two  = Db::name('customer')->where([['id', '<>', $customerId],['telephone', '=', $telephone],['shop_id','=',$inShopId]])->find();
                    if($info_two){
                        $this->error = '客户在【'.$inShopFind['shop_name'].'】已存在资料，转入门店类型相同，无法转入';
                        return false;
                    }
                }
            }
           
            if($is_information == 1){
                $this->sendSms($info['telephone'],['group'=>$inShopFind['shop_name'],'address'=>$inShopFind['address'],'tel'=>$inShopFind['shop_phone']]);
            }
            // print_r(123456);
            // exit();
            $updateData = [
                'shop_id'     => $inShopId,
                'turn_status' => 1,
                'nurse_id'    => 0,
                'update_time' => time()
            ];
            $bool = Db::name('customer')->where('id', '=', $customerId)->update($updateData);
            if ($bool) {
                $data = [
                    'customer_id' => intval($request['customer_id']),
                    'out_shop_id' => $outShopId,
                    'in_shop_id'  => $inShopId,
                    'operator'     => $user_id,
                    'reason'      => trim($request['reason']),
                    'create_time' => time(),
                    'update_time' => time()
                ];
                $settingId = $this->insertGetId($data);
                $inshopInfo = Db::name('shop')->where('shop_id', '=', $inShopId)->find();
                $saveData = [];
                if($inshopInfo['type'] == 1){
                    $bindWhere = [];
                    $bindWhere['shop_id'] = $inShopId;
                    $bindWhere['customer_id'] = $customerId;
                    $bindInfo = Db::name('customer_bind')->where($bindWhere)->find();
                    if (empty($bindInfo)){
                        $saveData['fcustId'] = 0;
                        $saveData['king_no'] = '';
                        Db::name('customer')->where('id', '=', $customerId)->update($saveData);
                    }else{
                        $saveData['fcustId'] = $bindInfo['fcustId'];
                        $saveData['king_no'] = $bindInfo['king_no'];
                        Db::name('customer')->where('id', '=', $customerId)->update($saveData);
                    }
                }else{
                        $saveData['fcustId'] = 0;
                        $saveData['king_no'] = '';
                        Db::name('customer')->where('id', '=', $customerId)->update($saveData);
                }
                if ($settingId) {					
					foreach ($customer_balanceList as $key1 => $vall){
						
						$saveshopID['shop_id'] = $inShopId;
						Db::name('customer_balance')->where('id', '=', $vall['id'])->update($saveshopID);	
					}
					
                    $this->error = '转店成功';
                    return true;
                }
            }
        // } catch (\Exception $e) {
        //     return $e->getMessage();
        // }

        $this->error = '转店失败';
        return false;
    }
    
    function send_post($url, $post_data){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        /**配置返回信息**/
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);//获取的信息以文件流的形式返回，不直接输出
        curl_setopt($curl, CURLOPT_HEADER, 0);//不返回header部分
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); //禁止 cURL 验证对等证书
        curl_setopt($curl, CURLOPT_POST, 1); //支持post提交数据
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
        $code = 200; //执行成功
        $data = curl_exec($curl);
        //捕抓异常
        if (curl_errno($curl)) {
          $code = 400; //执行异常
          $data = curl_error($curl);
        }
        curl_close($curl);
        // print_r($data);exit;
        // return array('code' => $code, 'data' => json_decode($data, true));
    }
    public  function  sendSms($phone,$data)
    {
        // print_r(111);exit;
        $group   = $data['group'] ?? '';
        $address = $data['address'] ?? '';
        $tel     = $data['tel'] ?? '';
        // print_r(urlencode("#code#=1234"));exit;
        $params = [
                      'apikey' => '9616eb7d8bd7ff79ca24af3fad8f192b',
                      'mobile' => $phone,
                      'tpl_id' => '3614628',
                      'tpl_value' =>('#group#').'='.$group.'&'.('#address#').'='.$address.'&'.('#tel#').'='.$tel
                    ];
        $param = '';
        foreach($params as $key => $val){
          $param .= urlencode($key).'='.urlencode($val).'&';
        }
        $param = substr($param,0,strlen($param)-1);
    
        // print_r($param);//exit;
        $a = $this->send_post("https://sms.yunpian.com/v2/sms/tpl_single_send.json", $param);
        // print_r($a);exit;
    }
}
